﻿
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { shopName, ADMIN_APP, serviceHost } from 'share/common';
import { MasterPage } from 'admin/masterPage';
// import { siteMap } from 'admin/pageNodes';
import * as ui from "maishu-ui-toolkit";
import 'jquery-ui';
import { Application } from "maishu-chitu-react"
import { ImageService } from "maishu-services-sdk";
import * as chitu from "maishu-chitu";

let { protocol } = location;
ImageService.baseUrl = `${protocol}//${serviceHost}/image`;

// for (let key in siteMap.nodes) {
//     if (typeof siteMap.nodes[key].action == 'string') {
//         siteMap.nodes[key].action = wrapAction(siteMap.nodes[key].action);
//     }
// }

export class AdminApplication extends Application {

    private masterPage: MasterPage;

    constructor() {
        super();

        ui.dialogConfig.dialogContainer = document.querySelector('.dialog-container') as HTMLElement;
        this.createMasterPage();
        this.error.add((app, err) => this.errorHandle(err));
    }


    // run() {
    //     if (!location.hash)
    //         this.redirect(siteMap.nodes.user_login);

    //     super.run();
    // }

    createMasterPage() {
        let element = document.createElement('div');
        document.body.insertBefore(element, document.body.children[0]);
        this.masterPage = ReactDOM.render(<MasterPage app={this} />, element) as any;
        document.title = shopName;
    }


    // createService<T extends Service>(type?: chitu.ServiceConstructor<T>): T {
    //     let service = new type();
    //     service.error.add((sender, err) => {
    //         this.error.fire(this, err, this.currentPage);
    //     })
    //     return service;
    // }

    // loadCSS(path: string) {
    //     // let pageNode = siteMap.nodes[pageName];
    //     // console.assert(pageNode != null);
    //     // console.assert(typeof pageNode.path == 'string');
    //     requirejs([`less!${path}`], function () {
    //         console.log(`load less!${path}`);
    //     });
    // }

    protected createPageElement(pageName: string): HTMLElement {
        let element = document.createElement('div');
        console.assert(this.masterPage.viewContainer != null, 'view container cannt be null.');
        this.masterPage.viewContainer.appendChild(element);
        return element;
    }

    redirect(node: { name: string } | string, args?) {
        let pageName: string = typeof node == 'string' ? node : node.name
        return super.redirect(pageName, args);
    }

    private errorHandle(err: Error) {
        switch (err.name) {
            case '600':     //600 为未知异常
            default:
                ui.alert({ title: '错误', message: err.message });
                console.log(err);
                break;

            case '710':
            case '724':     //724 为 token 失效
            case '601':     //601 为用户未登录异常
                // var currentPage = this.currentPage;
                // let isLoginPage = currentPage.name == (siteMap.nodes.user_login).name;
                // if (isLoginPage) {
                //     return;
                // }
                // this.redirect(siteMap.nodes.user_login, { return: app.createUrl(currentPage.name, currentPage.data) });
                break;
            case '725':
                ui.alert({ title: '错误', message: 'application-key 配置错误' });
                break;
        }
    }
}

function wrapAction(path: string): chitu.Action {

    let action = (page: chitu.Page) => {
        requirejs([path],
            (exports) => {
                console.assert(typeof exports.default == 'function');

                if ((exports.default as Function).prototype.isReactComponent) {
                    let reactElement = React.createElement(exports.default);
                    ReactDOM.render(reactElement, page.element);
                    return;
                }


                exports.default(page);
                return;
            },
            (err) => {
                app.error.fire(app, err, app.currentPage);
            }
        )
    }

    return action;
}




export let app: AdminApplication = window[ADMIN_APP] = window[ADMIN_APP] || new AdminApplication();

export default app;
